import React from 'react';
import { Upload, Icon, Modal } from 'antd';
import { connect } from 'dva';

const imageOrigin = 'http://images.zxgvip.com/';

@connect(({ global }) => ({ token: global.uploadToken }))
class ImagesUploader extends React.Component {
  constructor(props) {
    super(props);
    const { value } = props;
    const result = value ? `${imageOrigin}${value}` : '';
    this.state = {
      previewVisible: false,
      previewImage: result,
      fileList: [],
    };
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  beforeUpload = () => {
    const { dispatch } = this.props;
    return new Promise(async resolve => {
      await dispatch({ type: 'global/updateUploadToken' });
      resolve();
    });
  };

  handleChange = ({ fileList, file }) => {
    this.setState({ fileList });
    if (file.status === 'done') {
      const { onChange } = this.props;
      const data = fileList.map(({ response }) => response.hash);
      onChange(data);
    }
  };

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const { token } = this.props;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          action="https://up.qiniup.com"
          listType="picture-card"
          fileList={fileList}
          data={{ token }}
          beforeUpload={this.beforeUpload}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 12 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default ImagesUploader;
